import taos
import random
import sys
import datetime
import logging
import sys
from . import config

# 加入日志
# 获取logger实例
logger = logging.getLogger("baseSpider")
# 指定输出格式
formatter = logging.Formatter('%(asctime)s\
              %(levelname)-8s:%(message)s')
# 文件日志
file_handler = logging.FileHandler("../logs/taos.log")
file_handler.setFormatter(formatter)
# 控制台日志
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)

# 为logge添加具体的日志处理器
logger.addHandler(file_handler)
logger.addHandler(console_handler)

logger.setLevel(logging.INFO)


class TdengineConnector():
    # 构造函数,初始化数据库连接
    def __init__(self, params=None):
        # self.sql = sql
        self.params = params
        self.conn = None
        self.cur = None

    def connectiondatabase(self):
        #print(config.db_config['host'], config.db_config['username'],
        #      config.db_config['password'], config.db_config['database'], config.db_config['charset'])
        try:
            self.conn = taos.connect(host=config.db_config['host'], user=config.db_config['username'],
                                        password=config.db_config['password'], config=config.db_config['cfg'])
            # self.c1 = self.conn.cursor()
        except:
            logger.error("connectDatabase failed")
            return False
        self.cur = self.conn.cursor()
        self.cur.execute('use db')
        return True

    # 关闭数据库

    def closedatabase(self):
        # 如果数据打开，则关闭；否则没有操作
        if self.conn and self.cur:
            self.cur.close()
            self.conn.close()
        return True

    # 执行数据库的sq语句,主要用来做插入操作
    def execute(self, sql):
        self.connectiondatabase()
        try:
            if self.conn and self.cur:
                # 正常逻辑，执行sql，提交操作
                self.cur.execute(sql, self.params)
                self.conn.commit()
        except Exception as err:
            logger.error("execute failed: " + sql)
            logger.error("error info:" + err)
            # logger.error("params: " + self.params)
            self.closedatabase()
            return False
        return True

    # 用来查询表数据
    def select(self, sql):
        self.connectiondatabase()
        self.cur.execute(sql, self.params)
        result = self.cur.fetchall()
        #print(result)
        return self.rows2array(result)

    def rows2array(self, data):
        '''transfer tuple to array.'''
        result = []
        for da in data:
            # if type(da) is not dict:
            #     raise Exception('Format Error: data is not a dict.')
            result.append(da)
        return result
